﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RolePlayingGame
{
    public class ConsoleRenderer : IRenderer
    {
        //Borrowed from "ParticleSystem", then modified for single char objects
        
        int renderContextMatrixRows;
        int renderContextMatrixCols;
        char[,] renderContextMatrix;

        public ConsoleRenderer(int visibleConsoleRows, int visibleConsoleCols)
        {
            Console.Clear();
            renderContextMatrix = new char[visibleConsoleRows, visibleConsoleCols];
            Console.OutputEncoding = Encoding.Unicode;
            this.renderContextMatrixRows = renderContextMatrix.GetLength(0);
            this.renderContextMatrixCols = renderContextMatrix.GetLength(1);

            this.ClearQueue();
        }

        public void EnqueueForRendering(IRenderable obj)
        {
            char objImage = obj.GetSymbol();

            Coord objCenter = obj.GetLocation();

            if (objCenter.X < 0 || objCenter.Y < 0 || objCenter.X >= renderContextMatrixCols || objCenter.Y >= renderContextMatrixRows)
            {
                return;
            }
            renderContextMatrix[objCenter.Y, objCenter.X] = objImage;
        }

        public void RenderAll()
        {
            Console.SetCursorPosition(0, 0);

            StringBuilder scene = new StringBuilder();

            for (int row = 0; row < this.renderContextMatrixRows; row++)
            {
                for (int col = 0; col < this.renderContextMatrixCols; col++)
                {
                    scene.Append(this.renderContextMatrix[row, col]);
                }

                scene.Append(Environment.NewLine);
            }

            Console.WriteLine(scene.ToString());
        }

        public void ClearQueue()
        {
            for (int row = 0; row < this.renderContextMatrixRows; row++)
            {
                for (int col = 0; col < this.renderContextMatrixCols; col++)
                {
                    this.renderContextMatrix[row, col] = ' ';
                }
            }
        }
    }
}
